package com.config;

import com.utils.Commons;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;

@Component
public class MyInterceptor implements HandlerInterceptor { //自定义拦截类

    private static final Set<String> exUrl = new HashSet<>(); //白名单
    static {
        exUrl.add("/login");
        exUrl.add("/toLogin");
        exUrl.add("/logout");
        exUrl.add("/uploadFile");
        exUrl.add("/download");
        exUrl.add("/toupload");
        exUrl.add("/todownload");
        exUrl.add("/hello");
        exUrl.add("/register");
        exUrl.add("/toRegister");
        exUrl.add("/admin/login");
        exUrl.add("/admin/toLogin");
        exUrl.add("/test");
    }

    @Autowired
    private Commons commons;

    //自定义拦截规则，@return true放行，false拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("userName: " + request.getParameter("userName"));
//        System.out.println("password: " + request.getParameter("pwd"));
        String uri = request.getRequestURI();
        if (exUrl.contains(uri)) return true;
        HttpSession session = request.getSession();
//        Object user = session.getAttribute("user"); //登录过设置 user 字段
//        if (user == null) {
//            response.sendRedirect("/login"); //重定向
//            return false;
//        }
        if (uri.contains("/admin")) {
            Object admin = session.getAttribute("admin");
            if (admin == null) { //没有会话对象，管理员未登录
                response.sendRedirect("/admin/login");
                return false;
            }
            request.setAttribute("admin", admin);
        } else {
            Object user = session.getAttribute("user");
            if (user == null) { //没有会话对象，用户未登录
                response.sendRedirect("/login");
                return false;
            }
            request.setAttribute("user", user);
        }
        return true;
    }

    //controller 方法调用完毕后，执行此方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        request.setAttribute("commons", commons);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("afterCompletion");
    }
}
